#include "Db.h"

BindldDbLS *BindldDbLS::Bindld = NULL;
BindldDbLS::BindldDbLS() {
    std::string create_db =
        "create table if not exists Bindld (faceld TEXT primary key, userld "
        "TEXT);";
    char *zErrMsg = NULL;
    char **azResult = NULL;  // 二维数组存放结果
    const char rec_Bindld_db_path[] = "bindusrid.db";
    int ret = sqlite3_open(rec_Bindld_db_path, &g_db_);
    if (ret != SQLITE_OK) {
        sqlite3_close(g_db_);
        sqlite3_free(zErrMsg);
        return;
    }

    ret = sqlite3_exec(g_db_, create_db.c_str(), NULL, NULL, &zErrMsg);
    if (ret != SQLITE_OK) {
        // pploge("[LS] create LSBindld.db error");
        std::cout << create_db << std::endl;
        exit(0);
        sqlite3_free(zErrMsg);
    } else {
        // pplogd("[LS] create LSBindld.db success");
    }
}

BindldDbLS::~BindldDbLS() {
    if (Bindld != NULL) {
        delete Bindld;
    }
    if (g_db_ != NULL) {
        sqlite3_close(g_db_);
    }
}

BindldDbLS *BindldDbLS::Instance() {
    if (NULL == Bindld)
        if (NULL == Bindld) Bindld = new BindldDbLS();

    return Bindld;
}

bool BindldDbLS::insert(const char *faceId, const char *userId) {
    char *zErrMsg = NULL;
    char tmp[1024 * 1024] = {0};
    sprintf(tmp, "insert into Bindld values('%s','%s')", faceId, userId);

    printf("[LS] [Sqlite] %s", tmp);
    int ret = sqlite3_exec(g_db_, tmp, NULL, NULL, &zErrMsg);
    if (ret != SQLITE_OK) {
        // pploge("[LS] [Sqlite] insert fail code:%d, fail reason:%s", ret,
        //        zErrMsg);
        sqlite3_free(zErrMsg);
        return false;
    } else {
        printf("[LS] [Sqlite] insert sucess name: %s\n", faceId);
        return true;
    }
}

std::string BindldDbLS::getUserIdByFaceId(const char *faceId) {
    // 准备SQL查询语句
    const char *query = "select * from bindld where faceld = ?1";
    sqlite3_stmt *pStmt;
    sqlite3_prepare_v2(g_db_, query, strlen(query), &pStmt, NULL);

    // 绑定faceId到查询的参数
    sqlite3_bind_text(pStmt, 1, faceId, -1, SQLITE_TRANSIENT);

    int hr = sqlite3_step(pStmt);

    std::string userId = "";
    if (hr == SQLITE_ROW) {
        userId = reinterpret_cast<const char *>(sqlite3_column_text(pStmt, 1));
    } else {
        std::cout << "No user found with the given faceId.\n";
    }

    sqlite3_finalize(pStmt);
    sqlite3_close(g_db_);

    return userId;
}